//
//  ZbarReaderViewController.m
//  XiKou
//
//  Created by chenxiaojuan on 14-5-1.
//  Copyright (c) 2014年 科创信息. All rights reserved.
//

#import "ZbarReaderViewController.h"


#import "DataDictDao.h"
@interface ZbarReaderViewController (){
    
    ZBarReaderView *_readerView;
    int _num;
    BOOL _upOrdown;
    NSTimer * _timer;
    UIImageView *_line;
    
}

@end

@implementation ZbarReaderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	self.title = @"扫一扫";
    
    float h = SCREEN_HEIGHT - 64;
    float y = 0;
    
//    if (!SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
//        h = self.view.frame.size.height;
//    }
//    
//    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
//        y = 64;
//    }
//    
//    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.1")) {
//        y = 0;
//        h += 64;
//    }
//    
//#ifdef __IPHONE_7_0
//    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
//        self.automaticallyAdjustsScrollViewInsets = NO;
//    }
//#endif
    
    [self addTitleBarWithBackBtn:@"扫一扫" needReturn:YES];
    
    _readerView = [[ZBarReaderView alloc] init];
    _readerView.frame = CGRectMake(0, 64, SCREEN_WIDTH, h);
    _readerView.readerDelegate = self;
    //关闭闪光灯
    _readerView.torchMode = 0;
    //扫描区域
    //    CGRect scanMaskRect = CGRectMake(60, CGRectGetMidY(readerView.frame) - 126, 200, 200);
    
    //处理模拟器
    if (TARGET_IPHONE_SIMULATOR) {
        ZBarCameraSimulator *cameraSimulator
        = [[ZBarCameraSimulator alloc]initWithViewController:self];
        cameraSimulator.readerView = _readerView;
    }
    
    [self.view addSubview:_readerView];
    
    //扫描区域计算
    //    _readerView.scanCrop = [self getScanCrop:scanMaskRect readerViewBounds:self.readerView.bounds];
    
    float yL = (h - 40 - 20 - 280) / 2;
    
//    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.1")) {
//        yL = (h - 40 - 20 - 280 - 64) / 2;
//    }
//    
//    if (!SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0")) {
//        yL = (h - 40 - 20 - 280 - 44) / 2;
//    }
    
 
    
    UIImageView * image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zbar_pick_bg"]];
    image.frame = CGRectMake(20, yL + y  + 50, 280, 280);
    [self.view addSubview:image];
    
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, image.frame.origin.y+280 +20, 280, 40)];// 40 20 280
    label.text = @"将二维码放入框内，即可自动扫描";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.lineBreakMode = 0;
    label.numberOfLines = 2;
    label.backgroundColor = [UIColor clearColor];
    [self.view addSubview:label];
    
    
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(30, 10, 220, 2)];
    _line.image = [UIImage imageNamed:@"zbar_line"];
    [image addSubview:_line];
    //定时器，设定时间过1.5秒，
    _timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self startChat];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width, height);
}

-(void)animation1
{
    if (_upOrdown == NO) {
        _num ++;
        _line.frame = CGRectMake(30, 10+2*_num, 220, 2);
        if (2*_num == 260) {
            _upOrdown = YES;
        }
    }
    else {
        _num --;
        _line.frame = CGRectMake(30, 10+2*_num, 220, 2);
        if (_num == 0) {
            _upOrdown = NO;
        }
    }
}

- (void)startChat{
    
    [_readerView start];
}

- (void) readerView: (ZBarReaderView*) readerView didReadSymbols: (ZBarSymbolSet*) symbols fromImage: (UIImage*) image{
    
    [_readerView stop];
    [_timer invalidate];
    _line.frame = CGRectMake(30, 10, 220, 2);
    _num = 0;
    _upOrdown = NO;
    
    NSString *tick = @"";

    
    for (ZBarSymbol *symbol in symbols) {
        tick =  symbol.data;
        
 
    }
 
    
    [DE serverCall:@"scan" params:@{@"ticket":tick,@"senderId":DE.userId } callback:
     ^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
         if (success && data) {
             NSString *event =[data objectForKey:@"event"];
             NSLog(@"扫一扫事件：%@",event);
             if ([@"subscribeApp"isEqualToString:event]) {
                 [self updataPublicApps];
                 
             }else if ([@"joinGroup"isEqualToString:event] || [@"becomeFriend"isEqualToString:event]) {
                 [self updataLoackContacts];
             }//20151117 二维码扫描登陆(传入参数string detail )
             else if([@"portalLogin"isEqualToString:event])
             {
                 ScanLoginViewController *scanLogin = [[ScanLoginViewController alloc]init];
                 scanLogin.sDetail = [data objectForKey:@"detail"];
                 scanLogin.srootVC = _srootVC;
                 [kAppDelegate.iCSDrawerController.navigationController pushViewController:scanLogin animated:NO];
                 return;
             }
             else if ([@"success"isEqualToString:event]) {
                 
             }
             else if ([@"failed"isEqualToString:event]) {
                 
                 
             }
             NSString *strtitle =data?[data objectForKey:@"detail"]:@"请求失败！";
             NSLog(@"扫一扫返回：%@",strtitle);
             UIAlertView *view =[[UIAlertView alloc] initWithTitle:@"提示" message:strtitle delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [view show];
         }
    }];
    
}

-(void)updataPublicApps{
    
    [DE serverCall:@"queryApps" params:@{@"1":@"1"} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
       
        if (success) {
            NSArray *array = [data objectForKey:@"apps"];
            
            [PublicAccountDao updataDBwithSQLiteStatement:array];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
            //获取应用分类字典表
            NSArray *appTypesArray = [data objectForKey:@"dict"];

            [DataDictDao updataDataDictWithType:appTypesArray dicttypeId:@"6"];
        }
        
    }];
    
}

-(void)updataLoackContacts{
    
    NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
    NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
    [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        if(success)
        {
            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)dealloc{
    [_timer invalidate];
}

@end
